package com.zxy.javaarithmetic.chapter_1_StackQueue;

import java.util.Stack;

/*
 *  @项目名：  study
 *  @包名：    com.zxy.javaarithmetic.chapter_1_StackQueue
 *  @文件名:   P_3_ReverseStackByRecursion
 *  @创建者:   zhangxy
 *  @创建时间:  2018/12/3 11:12
 *  @描述：    TODO
 */
public class P_3_ReverseStackByRecursion {

	public static void main(String[] args) {
		Stack<Integer> stack = new Stack<>();
		stack.push(1);
		stack.push(2);
		stack.push(3);
		stack.push(4);
		stack.push(5);

		System.out.println(stack);
		reverseStackByRecursion(stack);
		System.out.println(stack);
	}


	/**
	 * 通过递归函数逆序一个栈
	 * @param stack
	 * @return
	 */
	public static void reverseStackByRecursion(Stack<Integer> stack) {
		if (!stack.isEmpty()) {
			int lastData = getAndRemoveStackLastElement(stack);
			reverseStackByRecursion(stack);
			stack.push(lastData);
		}
	}

	/**
	 * 获取栈底数据
	 * @param stack
	 * @return
	 */
	private static int getAndRemoveStackLastElement(Stack<Integer> stack) {
		int data = stack.pop();
		if (stack.isEmpty()) {
			return data;
		} else {
			int lastData = getAndRemoveStackLastElement(stack);
			stack.push(data);
			return lastData;
		}
	}

}
